package com.syauto.sm;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.graphics.Bitmap;
import android.widget.TextView;

import com.syauto.data.SaleOrderData;
import com.syauto.net.WebImageBuilder;
import com.syauto.user.OrderInfo;
import com.syauto.user.UserInfo; 

public class OrderFormPreview extends BaseActivity {
	
	RelativeLayout relayout;
	LinearLayout loadlayout;
	ListView listView;
	Button btnOrderState;
	Button btnOrderDecide;
	TextView tUserName;
	TextView tPosition;
	TextView tRowV;
	TextView tDayV;
	TextView tMonthV;
	
	
	TextView textView = null;
	boolean isupdate = true;
	ProgressDialog pDialog = null;
	List<JSONObject> listJson;
	ThisArrayAdapter arrAda;
	Builder builder;
	String OrderDecideWhere = "";
	String OrderStateWhere = "";
	FormTask formTask;
	SaleOrderData data;
	WebImageBuilder oBitmap;
	private LayoutInflater inflater;
	
	public OrderFormPreview() {
		data = new SaleOrderData();
		oBitmap = new WebImageBuilder();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.e("onKeyDown","OrderFormPreview");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.order_preview_layout);
		inflater = LayoutInflater.from(OrderFormPreview.this);
		View view = inflater.inflate(R.layout.order_filter_layout, null);
		this.addContentView(view, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		loadlayout = (LinearLayout)this.findViewById(R.id.loadLayout);
		listView = (ListView)this.findViewById(R.id.lvOrderList);
		listView.setOnScrollListener(new listView_Scroll());
		listView.setOnItemClickListener(new listView_ItemClick());
		btnOrderState=(Button)this.findViewById(R.id.btnOrderState);
		btnOrderState.setOnClickListener(new Order_Click(R.id.btnOrderState));
		btnOrderDecide = (Button)this.findViewById(R.id.btnOrderDecide);
		btnOrderDecide.setOnClickListener(new Order_Click(R.id.btnOrderDecide));
		relayout = (RelativeLayout)this.findViewById(R.id.rlOrderIndex);
		tUserName = (TextView) this.findViewById(R.id.txtUserName);
		tUserName.setText(UserInfo.getUserName());
		tPosition = (TextView) this.findViewById(R.id.txtPosition);
		tPosition.setText(UserInfo.getPosiName());
		
		tRowV = (TextView) this.findViewById(R.id.txtRowV);
		tDayV = (TextView) this.findViewById(R.id.txtDayV);
		tDayV.setText("0");
		tMonthV = (TextView) this.findViewById(R.id.txtMonthV);
		tMonthV.setText("0");
		
		listJson = new ArrayList<JSONObject>();
		arrAda = new ThisArrayAdapter(this,R.layout.orderitemview,listJson);
		listView.setAdapter(arrAda);
		formTask = new FormTask();
		formTask.execute("");
	}
	
	@Override
	protected void handleTitleBarEvent(int paramInt) {
		
	}
	
 	class ThisArrayAdapter extends ArrayAdapter<JSONObject>
 	{
 		public ThisArrayAdapter(Context context, int textViewResourceId,
 				List<JSONObject> listdata)
 		{
 			super(context, textViewResourceId, listdata);
 		}
 		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			return makeItemView(listJson.get(position));
		}
		
		private View makeItemView(JSONObject jo) {
	        LayoutInflater inflater = (LayoutInflater)OrderFormPreview.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        View itemView = inflater.inflate(R.layout.orderitemview, null);

	        TextView oOrderGuid = (TextView)itemView.findViewById(R.id.tvOrderGuid);  
	        try {
				oOrderGuid.setText(jo.getString("OrderGuid"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        
	        TextView oClientName = (TextView)itemView.findViewById(R.id.tvClientName);  
	        try {
				oClientName.setText(jo.getString("ClientName"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

	        TextView oOrderID = (TextView)itemView.findViewById(R.id.tvOrderID);  
	        try {
				oOrderID.setText(jo.getString("OrderNo"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

	        TextView oOrderCars = (TextView)itemView.findViewById(R.id.tvOrderCars);  
	        try {
				oOrderCars.setText(jo.getString("Order_Car_CheXi"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        
	        TextView oOrderModels = (TextView)itemView.findViewById(R.id.tvOrderModels);  
	        try {
				oOrderModels.setText(jo.getString("Order_Car_CheXing"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        
	        TextView oOrderCarColor = (TextView)itemView.findViewById(R.id.tvOrderCarColor);  
	        try {
				oOrderCarColor.setText(jo.getString("Order_Car_Color"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        
	        TextView oOrderState = (TextView)itemView.findViewById(R.id.tvOrderState);  
	        try {
				oOrderState.setText(jo.getString("OrderStatus"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
	        
	        TextView oOrderName = (TextView)itemView.findViewById(R.id.tvOrderName);  
	        try {
				oOrderName.setText(jo.getString("UserName"));
			} catch (JSONException e1) {
			}
	        
			ImageView oCar = (ImageView) itemView.findViewById(R.id.ivCar);
			Bitmap bitmap;
			try {
				bitmap = oBitmap.returnBitMap(UserInfo.NET_IMAGE
						+ "?a="
						+ UserInfo.getAgency()
						+ "&n="
						+ URLEncoder.encode(oOrderCars.getText() + " "
								+ oOrderCarColor.getText(), "UTF-8")
						+ "&h=64&w=64", oOrderCars.getText() + " "
						+ oOrderCarColor.getText() + "_64_64.png");
				oCar.setImageBitmap(bitmap);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			bitmap = null;
			return itemView;
	    }
 	}
 	
	class Order_Click implements OnClickListener {
		
		String[] strDecide = null;
		boolean[] boolDecide = null;
		String[] strState = null;
		boolean[] boolState = null;
		int butID;
		
		public Order_Click(int butId)
		{
			butID = butId;
		}
		
		@Override
		public void onClick(View v) {
			
			builder = new AlertDialog.Builder(OrderFormPreview.this);
			
			switch(butID)
			{
				case R.id.btnOrderDecide:
					if (boolDecide == null)
					{
						strDecide = getResources().getStringArray(R.array.arrayDingDanPanDuan);
						boolDecide = new boolean[strDecide.length];
						for(int i = 0;i<strDecide.length;i++)
							boolDecide[i] = false;	
					}
					builder.setTitle(R.string.strDingDanPanDuan);
					builder.setMultiChoiceItems(strDecide, boolDecide, new OnMultiChoiceClickListener(){
						
						@Override
						public void onClick(DialogInterface dialog, int which, boolean isChecked) {
							boolDecide[which] = isChecked;
						}
						
					});
					
					break;
				case R.id.btnOrderState:
					if (boolState == null)
					{
						strState = getResources().getStringArray(R.array.arrayOrderState);
						boolState = new boolean[strState.length];
						for(int i = 0;i<strState.length;i++)
							boolState[i] = false;	
					}
					builder.setTitle(R.string.strOrderState);
					builder.setMultiChoiceItems(strState, boolState, new OnMultiChoiceClickListener(){
						
						@Override
						public void onClick(DialogInterface dialog, int which, boolean isChecked) {
							boolState[which] = isChecked;
						}
						
					});
					break;
			}

			builder.setPositiveButton(R.string.strYes, new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					
					switch(butID)
					{
						case R.id.btnOrderDecide:
							OrderDecideWhere = "";
							for(int i = 0;i<strDecide.length;i++)
							{
								if(boolDecide[i]) OrderDecideWhere += OrderDecideWhere == "" ? ""+i : ","+i;
							}
							break;
						case R.id.btnOrderState:
							OrderStateWhere = "";
							for(int i = 0;i<strState.length;i++)
							{
								if(boolState[i]) OrderStateWhere += OrderStateWhere == "" ? ""+(i*10) : ","+(i*10);
							}
							break;
					}

					listJson.clear();
					arrAda.clear();
					UserInfo.setPage(0);
					
					formTask = new FormTask();
					formTask.execute("");
				}

			});
			builder.setNegativeButton(R.string.strNo, null);
			builder.create().show();
			
		}
		
	}

	class listView_Scroll implements OnScrollListener
	{

		@Override
		public void onScroll(AbsListView paramAbsListView, int paramInt1,
				int paramInt2, int paramInt3) {
			/*
			if (paramInt1 + paramInt2 == paramInt3) {
				Log.e("e", paramInt1 + "#" + paramInt2 + "#" + paramInt3);
			}
			
			*/
		}

		@Override
		public void onScrollStateChanged(AbsListView paramAbsListView,
				int paramInt) {

			switch (paramInt) {
			case OnScrollListener.SCROLL_STATE_IDLE:
				if (paramAbsListView.getLastVisiblePosition() == (paramAbsListView.getCount() - 1) && isupdate) {
					isupdate = false;
					UserInfo.setPage(UserInfo.getPage() + 1);
					formTask = new FormTask();
					formTask.execute("");
				}
				break;
			}
		}
		
	}
	
	class listView_ItemClick implements OnItemClickListener
	{

		@Override             
		public void onItemClick(AdapterView<?> arg0, View view, int arg2,long arg3) {

			Intent intent = new Intent(OrderFormPreview.this,OrderInfoTabActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("orderid", ((TextView)view.findViewById(R.id.tvOrderGuid)).getText().toString());
			bundle.putString("orderno", ((TextView)view.findViewById(R.id.tvOrderID)).getText().toString());
			bundle.putString("orderstatic", ((TextView)view.findViewById(R.id.tvOrderState)).getText().toString());
			bundle.putString("username", ((TextView)view.findViewById(R.id.tvOrderName)).getText().toString());
			
			intent.putExtras(bundle);
			
			if(OrderInfo.ordermain != null)
			{
				if(!OrderInfo.ordermain.getOrder_ID().equals(bundle.getString("orderid")))
				{
					OrderInfo.ordermain = null;
					OrderInfo.orderdetail = null;
				}
			}
			OrderFormPreview.this.startActivityForResult(intent, 100);
		}
	}
	
	class FormTask extends AsyncTask<String, Integer, String>
	{
		@Override
		protected void onPreExecute() {
			//super.onPreExecute();
			loadlayout.setVisibility(View.VISIBLE);
			//pDialog = ProgressDialog.show(OrderFormPreview.this, null, getString(R.string.strLoad));
		}
		
		@Override
		protected String doInBackground(String... params) {
			publishProgress(0);
			String json = "";
			try {
				json = data.getOrderSaleJson(
						UserInfo.getPage() + "",
						UserInfo.getRows() + "",
						UserInfo.getUserGuid(),
						OrderStateWhere,
						OrderDecideWhere);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			publishProgress(100);
			return json;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values[0]);
		}
		
		@Override
		protected void onPostExecute(String reslist) {
			if(reslist.length() > 0)
			{
				try {
					JSONObject jsontemp = new JSONObject(reslist);
					JSONArray jsonArray = new JSONArray(jsontemp.getString("Table"));
					
					for (int i = 0; i < jsonArray.length(); i++)
						listJson.add((JSONObject) jsonArray.get(i));
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				arrAda.notifyDataSetChanged();
				isupdate = true;
				//pDialog.dismiss();
				loadlayout.setVisibility(View.GONE);
			}
			else
			{
				Toast.makeText(OrderFormPreview.this.getApplicationContext(), 
						OrderFormPreview.this.getString(R.string.strNoData), 
						Toast.LENGTH_SHORT).show();
				loadlayout.setVisibility(View.GONE);
			}
			tRowV.setText(((UserInfo.getPage() + 1) * UserInfo.getRows()) + "");
			formTask = null;
		}
		
		@Override
		protected void onCancelled() {
			super.onCancelled();
			loadlayout.setVisibility(View.GONE);
			//pDialog.dismiss();
		}
	}
}
